package com.example.apigateway.filters;

import cn.hutool.core.util.StrUtil;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.ParseException;

/**
 * @author yangtao
 *     <p>这里我们还需要实现一个全局过滤器AuthGlobalFilter，当鉴权通过后将JWT令牌中的用户信息解析出来，然后存入请求的Header中，
 *     这样后续服务就不需要解析JWT令牌了，可以直接从请求的Header中获取到用户信息
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

  /**
   * 全局过滤器判断逻辑
   *
   * @param exchange
   * @param chain
   * @return
   */
  private static final String START_TIME = "startTime";

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
    ServerHttpRequest serverHttpRequest = exchange.getRequest();
    String token = serverHttpRequest.getHeaders().getFirst("Authorization");
    if (StrUtil.isEmpty(token)) {
      return chain.filter(exchange);
    }
    String ip = null; // IpUtil.getIp(serverHttpRequest);
    String method = serverHttpRequest.getMethod().name();
    String requestURI = serverHttpRequest.getURI().getPath();

    try {
      // 从token中解析用户信息并设置到Header中去
      String realToken = token.replace("Bearer ", "");
      JWSObject jwsObject = JWSObject.parse(realToken);
      String userStr = jwsObject.getPayload().toString();
      log.info("AuthGlobalFilter.filter() user:{}", userStr);
      ServerHttpRequest request = exchange.getRequest().mutate().header("user", userStr).build();
      exchange = exchange.mutate().request(request).build();
    } catch (ParseException e) {
      e.printStackTrace();
    }

    ServerWebExchange finalExchange = exchange;
    return chain
        .filter(exchange)
        .then(
            Mono.fromRunnable(
                () -> {
                  Long startTime = finalExchange.getAttribute(START_TIME);
                  if (startTime != null) {
                    Long executeTime = (System.currentTimeMillis() - startTime);
                    log.info(
                        String.format(
                            "%s >>> %s >>> %s >>> %s >>> %s ms",
                            requestURI, method, ip, token, executeTime));
                  }
                }));
  }

  /**
   * 顺序,数值越小,优先级越高
   *
   * @return
   */
  @Override
  public int getOrder() {
    return 0;
  }
}
